package com.cdel.akka.AkkainJAVA.demo6remote;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import akka.actor.ActorRef;
import akka.actor.UntypedActor;

//当这个actor接收到消息后,判断是否是结束标识,如果是就发送消息给reduceActor表示已经结束了.否则就计算这一行中的单词的个数,并把这个个数发送给reduceActor.
public class MapActor extends UntypedActor {

    /*reduce聚合的Actor*/
    private ActorRef actor = null;

    public MapActor(ActorRef inReduceActor) {
        actor = inReduceActor;
    }

    @Override
    public void preStart() throws Exception {
        System.out.println("启动MapActor:"+Thread.currentThread().getName());
    }

    @Override
    public void onReceive(Object message) throws Exception {
        if (message instanceof String) {
            String work = (String) message;
            // 计算这一行的单词情况
            List<Result> list = evaluateExpression(work);
            // 把这一行的单词情况发送给汇总的ReduceActor
            actor.tell(list, null);
        } else
            throw new IllegalArgumentException("Unknown message [" + message + "]");
    }

    /**
     * 用于分词 计算单词的数量的
     * @param line
     * @return
     */
    private List<Result> evaluateExpression(String line) {
        List<Result> list = new ArrayList<>();
        /*字符串分词器*/
        StringTokenizer parser = new StringTokenizer(line, " ");
        while (parser.hasMoreTokens()) {
            /*如果是,那么就判断是否是字母.然后把结果记录下来*/
            String word = parser.nextToken().toLowerCase();
            list.add(new Result(word, 1));
        }
        return list;
    }

}